﻿using DLC.Game.DataTable;
using DLC.Game.DataTable.ArchiveScriptableObject;
using DLC.Module.DataTable;
//using DLC.Game.DataTable;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
//using DLC.Game.DataTable.ArchiveScriptableObject;

namespace DLC.Example.ScriptableObject
{
	public class LoadDataTables : MonoBehaviour
	{
		public readonly IDataTableManager DataTableManager = new DataTableManager();

		public List<AssetReference> DataTableAssetRefs;

		void Start()
		{
			foreach (var dataAR in DataTableAssetRefs)
			{
				dataAR.LoadAssetAsync<IDataTableRowType>().Completed += OnDataTableLoaded;
				//shape.LoadAssetAsync<IDataTableRowType>().
			}
		}

		AssetReference GetAssetReference(AsyncOperationHandle<IDataTableRowType> obj)
		{
			foreach (var dataAR in DataTableAssetRefs)
			{
				if (dataAR.OperationHandle.Equals(obj))
				{
					return dataAR;
				}
			}
			return null;
		}

		private void OnDataTableLoaded(AsyncOperationHandle<IDataTableRowType> obj)
		{
			Debug.Log($"OnDataTableLoaded......{obj.Result.GetType()}");
			var da = GetAssetReference(obj);
			Debug.Log($"Asset.name......{da.Asset.name}");
			DataTableManager.AddDataTable(da.Asset.name, obj.Result);
			try
			{
				var table = DataTableManager.GetDataTable<ExcelExampleTempData>(da.Asset.name);
				//(table as ExcelExampleTest).InitializeDatas();
				Debug.Log($"Get Data Table table is {table}...{table.GetDataRow(1).Name}..{(table as ExcelExampleTemp).DataArray.Length}..{(table as ExcelExampleTemp).Count}");
            }
            catch(Exception e) {
				Debug.LogError(e.Message);
			}
        }
	}
}